<?php
namespace control;


//管理员后台-库存期初设置
class inventoryDefaultClass extends adIndexClass
{
	private const page        = 'inventoryDefault';
	private const table       = 'inventory_default';
	private const tableRecord = 'inventory_record';
	private const title       = '库存期初设置';
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            '供应商期初'=>[
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'应付金额',
                    'aliasName'=>'应付金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'其他应付金额',
                    'aliasName'=>'其他应付金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'预付金额',
                    'aliasName'=>'预付金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'结算日期',
                    'aliasName'=>'结算日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'业务员',
                    'aliasName'=>'业务员',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ],
            '客户期初'=>[
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'应收金额',
                    'aliasName'=>'应收金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'其他应收金额',
                    'aliasName'=>'其他应收金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'预收金额',
                    'aliasName'=>'预收金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期初金额',
                    'aliasName'=>'期初金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'结算日期',
                    'aliasName'=>'结算日期',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'业务员',
                    'aliasName'=>'业务员',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ],
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料分类',
                    'aliasName'=>'物料分类',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'库位名称',
                    'aliasName'=>'库位名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'期初数量',
                    'aliasName'=>'期初数量',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>true,
                ],
            ]
        };
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'clientSearch':
                $tr = [
                    'target_no'          => [
                        'name'  => "客户编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'target_name' => [
                        'name'  => "客户",
                        'width' => 200,
                    ],
                    'should_money'  => [
                        'name'  => "应收金额",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'other_money'  => [
                        'name'  => '其他应收金额',
                        'width' => 220,
                        'sort' => 1,
                    ],
                    'advance_money'  => [
                        'name'  => '预收金额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'balance'         => [
                        'name'  => '期初余额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'settlement_date'          => [
                        'name'  => '结算日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'salesman'          => [
                        'name'  => '业务员',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ]
                ];
                break;
            case 'supplierSearch':
                $tr = [
                    'target_no'          => [
                        'name'  => "供应商编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'target_name' => [
                        'name'  => "供应商",
                        'width' => 200,
                    ],
                    'should_money'  => [
                        'name'  => "应付金额",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'other_money'  => [
                        'name'  => '其他应付金额',
                        'width' => 220,
                        'sort' => 1,
                    ],
                    'advance_money'  => [
                        'name'  => '预付金额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'balance'         => [
                        'name'  => '期初余额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'settlement_date'          => [
                        'name'  => '结算日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'salesman'          => [
                        'name'  => '业务员',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ]
                ];
                break;
            default:
                $tr = [
                    'code'          => [
                        'name'  => "{l.inventoryDefault.homeForm.code}",
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => "{l.inventoryDefault.homeForm.name}",
                        'width' => 200,
                    ],
                    'typeName'  => [
                        'name'  => "{l.inventoryDefault.homeForm.type}",
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => '{l.inventoryDefault.homeForm.model}',
                        'width' => 220,
                    ],
                    'warehouse'  => [
                        'name'  => '{l.inventoryDefault.homeForm.warehouseName}',
                        'width' => 150,
                    ],
                    'unit'         => [
                        'name'  => '{l.inventoryDefault.homeForm.unit}',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '{l.inventoryDefault.homeForm.openingQuantity}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'batch'          => [
                        'name'  => '{l.inventoryDefault.homeForm.batch}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'defaultPrice'          => [
                        'name'  => '{l.inventoryDefault.homeForm.price}',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'total'          => [
                        'name'  => '{l.inventoryDefault.homeForm.total}',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '{l.inventoryDefault.homeForm.state}',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "产品分类" => materialClass::typeSelect(name:'typeId', title: '请选择'),
                    L('inventoryDefault.homeForm.code')   => text(array("name" => "code")),
                    L('inventoryDefault.homeForm.name')   => text(array("name" => "name")),
                ],
                [
                    L('inventoryDefault.homeForm.model')   => text(array("name" => "model")),
                    L('inventoryDefault.homeForm.warehouse')  => selectMultiple(['table' => 'warehouse', 'sqlField' => 'name', 'sqlId' => 'id', "where" => " coid = '" . self::$coid . "' and state = '启用' ", 'name' => 'warehouseId', 'class' => 'width200']),
                    L('inventoryDefault.homeForm.state') => select(["name" => "state", 'option' => [1 => '已确认', 0 => '未确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*期初设置-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."',classify:'库存期初'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',classify:'库存期初'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('inventoryDefault', 'operate', {'type': 'inventoryDefaultDelete', target:'库存期初设置' })\">".L('inventoryDefault.homeForm.del')."</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('inventoryDefault', 'operate', {'type': 'sure'})\">".L('inventoryDefault.homeForm.sureIn')."</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

	/**
	 * 列表页-查询结果
	 *
	 * @return string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$where = " `coid` = '" . self::$coid . "' ";
		// 仓库
		if ($this->post('warehouseId')) {
			$where .= " AND warehouseId ='" . $this->post('warehouseId') . "'";
		}
		if ($this->post('state') != '') {
			$where .= " AND state ='" . $this->post('state') . "'";
		}
		$mwhere = search([
			"like" => [
				'code'   => $this->post('code'),
				'name'   => $this->post('name'),
				'model'  => $this->post('model'),
				'typePath'  => $this->post('typeId'),
			],
		]);
		if ($mwhere) {
			$where .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate     = [
				"box" => ["name" => "listId", "value" => $array['id']],
			];
			$material     = query('material', " id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'typeName':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'warehouse':
                        $warehouse    = query('warehouse', " id = '$array[warehouseId]' ");
                        $row[] = $warehouse['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'defaultPrice':
                        $row[] = self::lostZero($array['defaultPrice'],'pricePrecision');
                        break;
                    case 'total':
                        $row[] = self::formattingFigure($array['num'] * $array['defaultPrice']);
                        break;
                    case 'state':
                        $row[] = ($array['state'] == 1 ? '已确认' : '未确认');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act    = $this->post('type') ?? '';
		$word   = false;
		$append = [];
		switch ($act) {
			case 'clientDefaultDelete':
				$act      = 'del';
				$msg      = L('inventoryDefault.operate.delClient');
				$title    = L('inventoryDefault.operate.clientMsg');
				$function = 'clientDefaultDelete';
				$form     = 'listForm,' . $this->get['cla'] . 'OperateForm';
				$word     = true;
				break;
			case 'supplierDefaultDelete':
				$act      = 'del';
				$msg      = L('inventoryDefault.operate.delSupplier');
				$title    = L('inventoryDefault.operate.supplierMsg');
				$function = 'supplierDefaultDelete';
				$form     = 'listForm,' . $this->get['cla'] . 'OperateForm';
				$word     = true;
				break;
			case 'sure':
				$act      = 'edit';
				$msg      = L('inventoryDefault.operate.sureInventory');
				$title    = L('inventoryDefault.operate.inventoryMsg');
				$function = 'sureEdit';
				$form     = 'listForm,' . $this->get['cla'] . 'OperateForm';
				$word     = true;
				$append   = [
					[
                        L('inventoryDefault.operate.type') => radio(['name' => "type", 'class' => 'text', 'option' => [1 => L('inventoryDefault.operate.sureChoice') , 2 => L('inventoryDefault.operate.allNotSure')], 'checked' => 1]),
					],
				];
				break;
			default:
				$act      = 'del';
				$msg      = L('inventoryDefault.operate.delPeriod');
				$title    = self::page . 'Delete';
				$function = 'isDelete';
				$form     = 'listForm,' . $this->get['cla'] . 'OperateForm';
				break;
		}
		if (!$this->power('inventoryDefault', $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('inventoryDefault.operate.warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'pwd'      => false,
				'word'     => $word,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 批量确认库存期初数据
	 *
	 * @return string
	 */
	public function sureEdit(): string
	{
		if ($this->post('type') == 1) {
			$listId = $this->post('listId');
		} else {
			$sql    = $_SESSION[self::page]['sql'];
			$all    = self::sqlFind($sql);
			$listId = array_column($all, 'id');
		}
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('inventoryDefault.sureEdit.power');
		} elseif (empty($listId)) {
			$json['warn'] = L('inventoryDefault.sureEdit.none');
		} else {
			$orderId          = self::getId();
			$field            = [
				'id'          => $orderId,
				'type'        => '其他入库',
				'subCategory' => '库存期初',
				'classify'    => 1,
				'warehouseId' => '0000',
				'state'       => '已入库',
				'coid'        => self::$coid,
				'stid'        => $this->control['stid'],
				'orderDate'   => $this->date,
			];
			$orderNo          = codeTemplateClass::generateCode('inStockOther', [
				'prefix' => 'QTRK' . date('Ymd'),
				'table'  => 'inventory',
				'field'  => 'orderNo',
				'where'  => " AND coid = '" . self::$coid . "' ",
			], $field);
			$field['orderNo'] = $orderNo;
			$json['warn']     = static::insert(["table" => 'inventory', "field" => $field,]);
			//库存变动记录
            $changeId          = self::getId();
            $fieldChanges            = [
                'id'          => $changeId,
                'coid'        => self::$coid,
                'type'        => '其他入库',
                'classify'    => 1,
                'confirmTime' => $this->time,
                'reviewTime'  => $this->time,
                'state'       => '已复核',
                'stid'        => $this->control['stid'],
            ];
            $orderNo          = codeTemplateClass::generateCode('inStock', [
                'prefix' => 'RKD' . date('Ymd'),
                'table'  => 'inventory_changes',
                'field'  => 'orderNo',
                'where'  => " AND coid = '" . self::$coid . "' ",
            ], $fieldChanges);
            $fieldChanges['orderNo'] = $orderNo;
            $warn     = static::insert(["table" => 'inventory_changes', "field" => $fieldChanges]);
            if($warn != '新增成功'){
                $json['warn'] = L('inventoryDefault.sureEdit.buildFailed');
            }
			if ($json['warn'] == '新增成功') {
				$this->startTrans();
				$isPass = true;
				$text   = $warn = "";
				$x      = 0;
				//$batch  = inStockClass::getBatchNo('库存期初');
				foreach ((array)$listId as $id) {
					$info = query(self::table, " id = '$id' ");
					if ($info['state'] == 1) {
						$warn = L('inventoryDefault.sureEdit.sureFail');
					} else {
						static::update([
							"table" => 'inventory_default',
							"field" => ['state' => 1],
							"where" => " id = '$id' ",
						]);
						$material = query("material", " id = '$info[materialId]' ");
						if (empty($material['positionId']) || $info['warehouseId'] != $material['warehouse']) {
							$material['positionId'] = inventoryBalanceClass::matchLocation($info['warehouseId']);
						}
						$fieldTwo = [
							'id'            => self::getId(),
							'coid'          => self::$coid,
							'orderId'       => $orderId,
							'materialId'    => $info['materialId'],
							'batch'         => $info['batch'],
							'num'           => $info['num'],
							'price'         => $info['defaultPrice'],
							'unit'          => $material['unit'],
							'warehouseId'   => $info['warehouseId'],
							'money'         => self::formattingFigure($info['num'] * $info['defaultPrice']),
						];
						//新增
						$warn = static::insert([
							"table" => 'inventory_detail',
							"field" => $fieldTwo,
						]);
						if ($warn != '新增成功') {
							$isPass       = false;
							$json['warn'] = $warn;
							break;
						}
						//库存变动记录明细
                        $fieldThree = [
                            'id'            => self::getId(),
                            'coid'          => self::$coid,
                            'orderId'       => $changeId,
                            'materialId'    => $info['materialId'],
                            'orderNum'      => $info['num'],
                            'batch'         => $info['batch'],
                            'num'           => $info['num'],
                            'unit'          => $material['unit'],
                            'price'         => $info['defaultPrice'],
                            'sourceTable'   => 'inventory_detail',
                            'sourceId'      => $fieldTwo['id'],
                            'sourceNo'      => $field['orderNo'],
                            'warehouseId'   => $info['warehouseId'],
                        ];
                        //新增
                        $warn = static::insert([
                            "table" => 'inventory_changes_detail',
                            "field" => $fieldThree,
                        ]);
                        if ($warn != '新增成功') {
                            $isPass       = false;
                            $json['warn'] = $warn;
                            break;
                        }
						inventoryDefaultClass::recordInventoryPrice($info['materialId'], $info['num'], $info['defaultPrice'],date('Y-m-d H:i:s',strtotime("-356 day")));//计算记录加权平均单价
						$recordId = self::getId();
						$warn     = static::insert([
							'table' => self::tableRecord,
							'field' => [
								'id'            => $recordId,
								'coid'          => self::$coid,
								'warehouseId'   => $info['warehouseId'],
								'positionId'    => $material['positionId'],
								'materialId'    => $info['materialId'],
								'batch'         => $info['batch'],
								'num'           => $info['num'],
								'inventoryId'   => $orderId,
								'inventoryMxId' => $fieldTwo['id'],
								'changesId' => $fieldThree['id'],
							],
						]);
						if ($warn != '新增成功') {
							$isPass       = false;
							$json['warn'] = $warn;
							break;
						}
						if (!empty($material['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $material['positionId']]);
						//返回
						$warn = L('inventoryDefault.sureEdit.success');
						$x++;
					}
					$text .= str_replace(['{{id}}','{{materialId}}'], [$info['id'],$info['materialId']], lang('inventoryDefault.sureEdit.text')) . $warn . "。<br>";
				}
				if ($isPass == true) {
					$this->commitTrans();
					//添加日志
					$text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inventoryDefault.sureEdit.log')). "<br>" . $text;
					$this->logText(["type" => self::page, "text" => $text]);
					$_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('inventoryDefault.sureEdit.warn'));
					$json['warn']     = 2;
				} else {
					$this->rollback();
				}
			}
		}
		return json_encode($json, 320);
	}

	/**
	 * 批量删除
	 *
	 * @return string
	 */
	public function isDelete(): string
	{
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('inventoryDefault.isDelete.power');
		} elseif (empty($this->post('listId'))) {
			$json['warn'] = L('inventoryDefault.isDelete.none');
		} else {
			$text = $warn = "";
			$x    = 0;
			foreach ($this->post('listId') as $id) {
				$info = query(self::table, " id = '$id' ", 'id,state,materialId');
				if ($info['state'] == 1) {
					$warn = L('inventoryDefault.isDelete.fail');
				} else {
					delete(["table" => self::table, "where" => " id = '$id' "]);
					//返回
					$warn = L('inventoryDefault.isDelete.success');
					$x++;
				}
				$text .= str_replace(['{{id}}','{{materialId}}'], [$info['id'],$info['materialId']], lang('inventoryDefault.isDelete.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inventoryDefault.isDelete.log')) . "<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('inventoryDefault.isDelete.warn'));
			$json['warn']     = 2;
		}
		return json_encode($json, 320);
	}

	/**插入物料平均单价
	 *
	 * @param string $materialId 物料id
	 * @param float  $num           入库数量
	 * @param float  $price         入库单价
	 * @param string $time
	 * @return bool
	 */
	public static function recordInventoryPrice(string $materialId, float $num, float $price, $time = ''): bool
	{
		$total           = inventoryBalanceClass::inventoryNum($materialId); //库存数量
        $total = $total<0?0:$total;
		$inventory_price = query("inventory_price", " coid = '" . self::$coid . "' and materialId = '" . $materialId . "' order by id desc ", 'avgPrice');
		$oldAvgPrice     = empty($inventory_price['avgPrice']) ? 0 : (float)$inventory_price['avgPrice'];
		$avgPrice        = ($total + $num) > 0 ? self::formattingFigure(($oldAvgPrice * $total + $price * $num) / ($total + $num), 'pricePrecision') : 0;
		$field           = [
			'coid'          => self::$coid,
			'materialId'    => $materialId,
			'avgPrice'      => $avgPrice,
			'recordTime'    => static::isNull($time) ? date('Y-m-d H:i:s') : $time,
			'time'          => date("Y-m-d H:i:s"),
		];
		$warn            = static::insert(["table" => 'inventory_price', "field" => $field]);
		if (!in_array($warn, ['新增成功'])) {
			test('插入加权平均单价' . $warn);
		}
		return $warn;
	}

	/**
	 * 获取库存均价
	 *
	 * @param        $materialId
	 * @param        $unit
	 * @param string $time
	 * @return int|float
	 */
	public static function getInventoryPrice($materialId, $unit = '', $time = ''): int|float
	{
		$material = query('material', "id = '$materialId'");
		$where    = '';
		if ($time) {
			//带时分秒格式
			$where .= " and UNIX_TIMESTAMP(recordTime) <= UNIX_TIMESTAMP('" . $time . "')";
			if (date('Y-m-d', strtotime($time)) == $time) {
				//日期格式  取日期当前最早一条，如果没有，则取小于当天的最新一条
				$inventory_price = query("inventory_price", " coid = '" . self::$coid . "' and materialId = '" . $materialId . "' and date_format(recordTime,'%Y-%m-%d')='$time' order by id asc ");
				if ($inventory_price['id']) {
					$price = (float)$inventory_price['avgPrice'] ?: 0;
					return $unit ? machiningOrderClass::material_num_change($materialId, $unit, $material['unit']) * $price : $price;
				}
			}
		}
		$inventory_price = query("inventory_price", " coid = '" . self::$coid . "' and materialId = '" . $materialId . "' $where order by id desc ", 'avgPrice');
		$price           = (float)$inventory_price['avgPrice'] ?: 0;
		return $unit ? machiningOrderClass::material_num_change($materialId, $unit, $material['unit']) * $price : $price;
	}

    /** 根据计价规则获取入库单价
     * @param string $type inStockPrice:入库带出单价,outStockPrice:出库带出单价,refundPrice:退货/退料出库带出单价
     * @param string $materialId
     * @param string $unit
     * @param string $time
     * @return float
     */
    public static function pricingRules(string $type, string $materialId, $unit = '', $time = ''): float
    {
        $time = $time?:date("Y-m-d H:i:s");
        $parameters = optionSettingClass::getSetting('核算');
        $material = query("material", " id = '$materialId' ", "unit,costPrice");
        $unitNum = $unit ? machiningOrderClass::material_num_change($materialId, $unit, $material['unit']) : 1;  //单位数量转换
        $where = "";
        if ($time) {
            //带时分秒格式
            $where .= " and UNIX_TIMESTAMP(mx.time) <= UNIX_TIMESTAMP('" . $time . "')";
        }
        switch ($parameters[$type])
        {
            case '上次出库成本':
                $outStock = find(array("field"=>"mx.price,mx.unit","table"=>"inventory_detail as mx join inventory as a on mx.orderId = a.id","single"=>" mx.coid = '".self::$coid."' and mx.materialId = '$materialId' and a.classify = 0 and a.state = '已出库' {$where} order by UNIX_TIMESTAMP(mx.time) desc "));
                if(isset($outStock['price'])) {
                    $price = machiningOrderClass::material_num_change($materialId, $outStock['unit'], $material['unit']) * $outStock['price'];
                }else{
                    $price = 0;
                }
                break;
            case '结存成本':
                $price = self::getInventoryPrice($materialId,$unit,$time);
                break;
            case '上次入库成本':
                $inStock = find(array("field"=>"mx.price,mx.unit","table"=>"inventory_detail as mx join inventory as a on mx.orderId = a.id","single"=>" mx.coid = '".self::$coid."' and mx.materialId = '$materialId' and a.classify = 1 and a.state = '已入库' {$where} order by UNIX_TIMESTAMP(mx.time) desc "));
                if(isset($inStock['price'])) {
                    $price = machiningOrderClass::material_num_change($materialId, $inStock['unit'], $material['unit']) * $inStock['price'];
                }else{
                    $price = 0;
                }
                break;
            default:
                $price = $material['costPrice']*$unitNum;
        }
        $price = $price>0?$price:$material['costPrice']*$unitNum;
        //当按计价规则取的成本与参考成本差异率超比例时，取参考成本
        if($parameters['costRate']['option'] && $parameters[$type] != '参考成本') {
            $rate = (float)$parameters['costRate']['rate']/100;
            $referenceStart = self::formattingFigure($material['costPrice'] * (1 - $rate),'pricePrecision')*$unitNum;
            $referenceEnd = self::formattingFigure($material['costPrice'] * (1 + $rate),'pricePrecision')*$unitNum;
            if($price < $referenceStart || $price > $referenceEnd){
                $price = $material['costPrice']*$unitNum;
            }
        }
        return self::formattingFigure($price,'pricePrecision');
    }
	/**
	 * 下载模板
	 */
	public function downloadModel()
	{
        $templateId = $this->get('templateId');
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = L('inventoryDefault.downloadModel.power');
        }  else {
            $exampleData = [];
            $excel    = $this->excelHead();
            $fileName = '库存期初导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '物料编码'=>$example[0],
                            '物料名称'=>$example[1],
                            '物料分类'=>$example[2],
                            '规格型号'=>$example[3],
                            '仓库名称'=>$example[4],
                            '库位名称'=>$example[5],
                            '主单位'=>$example[6],
                            '期初数量'=>$example[7],
                            '批次'=>$example[8],
                            '单价'=>$example[9],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
			$text  = str_replace(['{{staffName}}'], [$this->control['name']], lang('inventoryDefault.downloadModel.log'));
			$this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/**
	 * Excel导入
	 */
	public function importData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power(self::page, 'import')) {
			$json['warn'] = L('inventoryDefault.importData.power');
        }else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list = 0;//excel第几行
			foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }

                    $cell['期初数量'] = self::formattingFigure(floatval($cell['期初数量']),'numPrecision');
                    if($cell['期初数量'] > 0) {
                        //'物料编号', '物料名称', '物料分类', '规格型号', '仓库名称', '库位名称', '主单位', '主单位期初数量', '批次', '单价'
                        $warehouse = query('warehouse', " coid = '" . self::$coid . "' AND name = '$cell[仓库名称]' ");
                        if (!$warehouse['id']) {
                            $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.notWarehouse')) . "<br>";
                        } elseif ($warehouse['state'] != '启用') {
                            $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.notStart')) . "<br>";
                        } else {
                            $positionId = query('warehouse_position', " orderId = '" . $warehouse['id'] . "' AND name = '$cell[库位名称]' AND name <> '' ")['id'];

                            $material = query('material', " coid = '" . self::$coid . "' AND code = '$cell[物料编码]' and model = '$cell[规格型号]' ");
                            if (!$material['id']) {
                                $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.notMaterial')) . "<br>";
                            } else {
                                $where = " warehouseId = '{$warehouse['id']}' and positionId = '$positionId' AND materialId = '{$material['id']}' AND state = 0 and batch = '$cell[批次]' ";
                                $otherInventoryRecord = query(self::table, $where);  //物料期初数据
                                if (preg_match(checkPrice, $cell['单价']) == 0) {
                                    $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.priceFormat')) . "<br>";
                                } elseif (!empty($otherInventoryRecord['id'])) {
                                    $text .= str_replace(['{{i}}','{{error}}'], [$row_list,L('inventoryDefault.importData.repeat')], lang('material.importData.error')) . "<br>";
                                } else {
                                    $this->startTrans();

                                    $num = machiningOrderClass::material_num_change($material['id'], $cell['主单位'], $material['unit'], $cell['期初数量']);
                                    $price = $num==0?0:self::formattingFigure($cell['期初数量'] * floatval($cell['单价']) / (float)$num, 'pricePrecision');
                                    $inventoryRecord = query(self::table, $where);
                                    $field = [
                                        'coid' => self::$coid,
                                        'warehouseId' => $warehouse['id'],
                                        'positionId' => $positionId,
                                        'materialId' => $material['id'],
                                        'num' => $num,
                                        'batch' => $cell['批次'],
                                        'defaultPrice' => $price,
                                        'time' => $this->time,
                                    ];
                                    if (static::isNull($inventoryRecord['id'])) {
                                        $field = array_merge($field, [
                                            'id' => self::getNo(),
                                        ]);
                                        $warn = static::insert(["table" => self::table, "field" => $field,]);
                                    } else {
                                        $warn = static::update(["table" => self::table, "field" => $field, 'where' => " id = '" . $inventoryRecord['id'] . "' "]);
                                    }
                                    if (in_array($warn, ['新增成功', '更新成功'])) {
                                        $this->commitTrans();
                                        // 更新数量
                                        $x++;
                                        $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.success')) . "<br>";
                                    } else {
                                        $this->rollback();
                                        $text .= str_replace(['{{i}}'], [$row_list], lang('inventoryDefault.importData.fail')) . "<br>";
                                    }
                                }
                            }
                        }
                    }
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$warn = str_replace(['{{x}}'], [$x], lang('inventoryDefault.importData.log'));
			$this->logText(["type" => self::page, "text" => $warn.$text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '您还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $material     = query('material', " id = '$array[materialId]'");
                $materialType = $material['typeName'];
                $warehouse    = query('warehouse', " id = '$array[warehouseId]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '物料编码'=>$material['code'],
                            '物料名称'=>$material['name'],
                            '物料分类'=>$materialType,
                            '规格型号'=> $material['model'],
                            '仓库名称'=>$warehouse['name'],
                            '主单位'=>  $material['unit'],
                            '主单位期初数量'=>self::lostZero($array['num'],'numPrecision'),
                            '批次'=>$array['batch'],
                            '单价'=>self::lostZero($array['defaultPrice'],'pricePrecision'),
                            '总价'=>self::formattingFigure($array['num'] * $array['defaultPrice']),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inventoryDefault.exportData.log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, lang('inventoryDefault.exportData.fileName').'.xlsx');
			exit(0);
		}
		$locationUrl = root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=home';
		header("Location:" . $locationUrl);
	}

    /*列表页-查询条件*/
    public function clientOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inventoryDefault.homeForm.client_no')   => text(array("name" => "target_no")),
                    L('inventoryDefault.homeForm.client_name')   => text(array("name" => "target_name")),
                    L('inventoryDefault.homeForm.salesman')   => text(array("name" => "salesman")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 客户期初
	 */
	public function client(): bool|string
	{
        $html = $this->clientOptions(false);
        //控件
        $button = "";
        if ($this->power('clientDefault', 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{classify:'客户期初',fun:'clientSearch',cla:'".self::page."',exportFun:'downloadClientModel',importFun:'importClientData'})\">导入</span>";
        }
        if ($this->power('clientDefault', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportClientData',classify:'客户期初'})\">导出</span>";
        }
        if ($this->power('clientDefault', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('inventoryDefault', 'operate', {'type': 'clientDefaultDelete', target:'客户期初设置' })\">删除所选</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户期初
	 *
	 * @return bool|string
	 */
	public function clientSearch(): bool|string
	{
		//like查询数组
		$like = array(
			"target_no"    => $this->post('target_no'),
			"target_name"  => $this->post('target_name'),
			"should_money" => $this->post('should_money'),
		);
		//全等查询数组
		$equal = array(
			'type' => '客户',
			'coid' => self::$coid,
		);

		$and = "";
		//获取查询结果
		$where                            = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
		$page                             = $this->page(array("table" => "current_unit_default", "where" => $where, "order" => $orderBy['orderBy']));
		$_SESSION['clientDefault']['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box" => array("name" => "listId", "value" => $array['id']),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'should_money':
                    case 'other_money':
                    case 'advance_money':
                    case 'balance':
                        $row[] = self::lostZero($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 批量删除
	 *
	 * @return string
	 */
	public function clientDefaultDelete(): string
	{
		if (!$this->power('clientDefault', "del")) {
			$json['warn'] = "您没有删除期初数据的权限";
		} elseif (empty($this->post('listId'))) {
			$json['warn'] = "您一个期初数据都没有选择呢";
		} else {
			$text = $warn = "";
			$x    = 0;
			foreach ($this->post('listId') as $id) {
				$info = query('current_unit_default', " id = '$id' ", 'id,coid,type,typeId,target_name');
				if (!empty($info['id'])) {
					$record = query("record", " coid = '$info[coid]' and type = '$info[type]' and typeId = '$info[typeId]' and sourceId <> '$info[id]' ");
					if (!empty($record['id'])) {
						$warn = "账户已存在其他变动记录，无法删除";
					} else {
						delete(["table" => 'current_unit_default', "where" => " id = '$id' "]);
						delete(["table" => 'record', "where" => " sourceTable = 'current_unit_default' and sourceId = '$id' "]);
						//返回
						$warn = "删除成功";
						$x++;
					}
				}
				$text .= "客户期初id【" . $info['id'] . "】，客户名称【" . $info['target_name'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "批量删除了客户期初，结果如下：<br>" . $text;
			$this->logText(["type" => 'clientDefault', "text" => $text]);
			$_SESSION['warn'] = "删除了" . $x . "个客户期初，详情见系统日志。";
			$json['warn']     = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 下载模板
	 */
	public function downloadClientModel()
	{
        $templateId = $this->get('templateId');
		if (!$this->power('clientDefault', 'import')) {
			$_SESSION['warn'] = '你还没有导入的权限';
        }  else {
            $exampleData = [];
            $excel    = $this->excelHead();
            $fileName = '客户期初导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit('客户期初'), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户编码'=>$example[0],
                            '客户名称'=>$example[1],
                            '应收金额'=>$example[2],
                            '其他应收金额'=>$example[3],
                            '预收金额'=>$example[4],
                            '期初金额'=>$example[5],
                            '结算日期'=>$example[6],
                            '业务员'=>$example[7],
                            '备注'=>$example[8],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
			$text  = $this->control['name'] . "下载了客户期初导入模板";
			$this->logText(["type" => 'clientDefault', "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/**
	 * Excel导入
	 */
	public function importClientData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power('clientDefault', 'import')) {
			$json['warn'] = '你还没有导入的权限';
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list = 0;//excel第几行
			foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit('客户期初') as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
					//'客户编码', '客户', '应收金额', '其他应收金额', '预收金额', '期初金额', '结算日期', '业务员', '备注'
					$kehu                 = query('kehu', " coid = '" . self::$coid . "' AND orderNo = '$cell[客户编码]' ");
					$where                = " coid = '" . self::$coid . "' AND type = '客户' AND typeId = '{$kehu['khid']}' ";
					$current_unit_default = query('current_unit_default', $where);
					$record               = query("record", " coid = '" . self::$coid . "' and type = '客户' and typeId = '$kehu[khid]' ");
					if (!$kehu['khid']) {
						$text .= "客户期初导入失败：第【{$row_list}】行无此客户<br>";
					} elseif ($record['id']) {
						$text .= "客户期初导入失败：第【{$row_list}】行此客户已存在账户变动记录<br>";
					} else {
						$this->startTrans();
						$field = [
							'coid'            => self::$coid,
							'type'            => '客户',
							'typeId'          => $kehu['khid'],
							'target_no'       => $kehu['orderNo'],
							'target_name'     => $kehu['companyName'],
							'should_money'    => self::formattingFigure(floatval($cell['应收金额'])),
							'other_money'     => self::formattingFigure(floatval($cell['其他应收金额'])),
							'advance_money'   => self::formattingFigure(floatval($cell['预收金额'])),
							'balance'         => self::formattingFigure(floatval($cell['期初金额'])),
							'settlement_date' => is_numeric($cell['结算日期']) ? date("Y-m-d", $cell['结算日期']) : $cell['结算日期'],
							'salesman'        => $cell['业务员'],
							'text'            => $cell['备注'],
							'time'            => $this->time,
						];
						if (static::isNull($current_unit_default['id'])) {
							$field = array_merge($field, [
								'id' => self::getNo(),
							]);
							$warn  = static::insert(["table" => 'current_unit_default', "field" => $field,]);
						} else {
							$field['id'] = $current_unit_default['id'];
							$warn        = static::update(["table" => 'current_unit_default', "field" => $field, 'where' => " id = '" . $current_unit_default['id'] . "' "]);
						}
						if (in_array($warn, ['新增成功', '更新成功'])) {
							//插入账户变动表
							$clientRecord = query('record', " coid = '" . self::$coid . "' and type = '客户' and typeId = '$kehu[khid]' and sourceTable = 'current_unit_default' and sourceId = '$current_unit_default[id]' ");
							$field        = [
								'coid'        => self::$coid,
								'type'        => '客户',
								'typeId'      => $kehu['khid'],
								'targetDate'  => $field['settlement_date'],
								'classify'    => '客户期初',
								'direction'   => '+',
								'money'       => $field['balance'],
								'balance'     => $field['balance'],
								'sourceTable' => 'current_unit_default',
								'sourceId'    => $field['id'],
								'text'        => $field['text'],
								'stName'      => $this->control['name'],
								'hiddenText'  => $this->date . '客户期初导入',
								'time'        => $this->time,
							];
							if (static::isNull($clientRecord['id'])) {
								$warn = static::insert(["table" => 'record', "field" => $field,]);
							} else {
								$warn = static::update(["table" => 'record', "field" => $field, 'where' => " id = '" . $clientRecord['id'] . "' "]);
							}
							if (in_array($warn, ['新增成功', '更新成功'])) {
								$this->commitTrans();
								// 更新数量
								$x++;
								$text .= "第【{$row_list}】行导入成功<br>";
							} else {
								$this->rollback();
							}
						} else {
							$this->rollback();
							$text .= "第【{$row_list}】行导入失败：插入失败<br>";
						}
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$this->logText(["type" => 'clientDefault', "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}

	/**
	 * 导出
	 */
	public function exportClientData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		if (!$this->power('clientDefault', 'export')) {
			$_SESSION['warn'] = '您还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => 'current_unit_default',
                    "where" => "id in ('".implode("','", $checkedId)."') order by list desc",
                ))['array'];
            }else{
                $sql   = $_SESSION['clientDefault']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户编码'=>$array['target_no'],
                            '客户'=>$array['target_name'],
                            '应收金额'=> self::lostZero($array['should_money']),
                            '其他应收金额'=>self::lostZero($array['other_money']),
                            '预收金额'=>self::lostZero($array['advance_money']),
                            '期初余额'=>self::lostZero($array['balance']),
                            '结算日期'=>$array['settlement_date'],
                            '业务员'=>$array['salesman'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

			$text = $this->control['name'] . "导出了客户期初设置";
			$this->logText(["type" => 'clientDefault', "text" => $text]);
			$this->excelOut($title, $data, '客户期初设置.xlsx');
			exit(0);
		}
		$locationUrl = root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=home';
		header("Location:" . $locationUrl);
	}

    /*列表页-查询条件*/
    public function supplierOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inventoryDefault.homeForm.supplier_no')   => text(array("name" => "target_no")),
                    L('inventoryDefault.homeForm.supplier_name')   => text(array("name" => "target_name")),
                    L('inventoryDefault.homeForm.salesman')   => text(array("name" => "salesman")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 供应商期初
	 */
	public function supplier(): bool|string
	{
        $html = $this->supplierOptions(false);
        //控件
        $button = "";
        if ($this->power('supplierDefault', 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{classify:'供应商期初',fun:'supplierSearch',cla:'".self::page."',exportFun:'downloadSupplierModel',importFun:'importSupplierData'})\">导入</span>";
        }
        if ($this->power('supplierDefault', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportSupplierData',classify:'供应商期初'})\">导出</span>";
        }
        if ($this->power('supplierDefault', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('inventoryDefault', 'operate', {'type': 'supplierDefaultDelete', target:'供应商期初设置' })\">删除所选</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 供应商期初
	 *
	 * @return bool|string
	 */
	public function supplierSearch(): bool|string
	{
		//like查询数组
		$like = array(
			"target_no"    => $this->post('target_no'),
			"target_name"  => $this->post('target_name'),
			"should_money" => $this->post('should_money'),
		);
		//全等查询数组
		$equal = array(
			'type' => '供应商',
			'coid' => self::$coid,
		);

		$and = "";
		//获取查询结果
		$where                              = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
		$page                               = $this->page(array("table" => "current_unit_default", "where" => $where, "order" => $orderBy['orderBy']));
		$_SESSION['supplierDefault']['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box" => array("name" => "listId", "value" => $array['id']),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'should_money':
                    case 'other_money':
                    case 'advance_money':
                    case 'balance':
                        $row[] = self::lostZero($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 批量删除
	 *
	 * @return string
	 */
	public function supplierDefaultDelete(): string
	{
		if (!$this->power('supplierDefault', "del")) {
			$json['warn'] = "您没有删除期初数据的权限";
		} elseif (empty($this->post('listId'))) {
			$json['warn'] = "您一个期初数据都没有选择呢";
		} else {
			$text = $warn = "";
			$x    = 0;
			foreach ($this->post('listId') as $id) {
				$info = query('current_unit_default', " id = '$id' ", 'id,coid,type,typeId,target_name');
				if (!empty($info['id'])) {
					$record = query("record", " coid = '$info[coid]' and type = '$info[type]' and typeId = '$info[typeId]' and sourceId <> '$info[id]' ");
					if (!empty($record['id'])) {
						$warn = "账户已存在其他变动记录，无法删除";
					} else {
						delete(["table" => 'current_unit_default', "where" => " id = '$id' "]);
						delete(["table" => 'record', "where" => " sourceTable = 'current_unit_default' and sourceId = '$id' "]);
						//返回
						$warn = "删除成功";
						$x++;
					}
				}
				$text .= "供应商期初id【" . $info['id'] . "】，供应商【" . $info['target_name'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "批量删除了供应商期初，结果如下：<br>" . $text;
			$this->logText(["type" => 'supplierDefault', "text" => $text]);
			$_SESSION['warn'] = "删除了" . $x . "个供应商期初，详情见系统日志。";
			$json['warn']     = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 下载模板
	 */
	public function downloadSupplierModel()
	{
        $templateId = $this->get('templateId');
		if (!$this->power('supplierDefault', 'import')) {
			$_SESSION['warn'] = '你还没有导入的权限';
        } else {
            $exampleData = [];
            $excel    = $this->excelHead();
            $fileName = '供应商期初导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit('供应商期初'), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '供应商编码'=>$example[0],
                            '供应商名称'=>$example[1],
                            '应付金额'=>$example[2],
                            '其他应付金额'=>$example[3],
                            '预付金额'=>$example[4],
                            '期初余额'=>$example[5],
                            '结算日期'=>$example[6],
                            '业务员'=>$example[7],
                            '备注'=>$example[8],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

			$text  = $this->control['name'] . "下载了供应商期初导入模板";
			$this->logText(["type" => 'supplierDefault', "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/**
	 * Excel导入
	 */
	public function importSupplierData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power('supplierDefault', 'import')) {
			$json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list = 0;
			foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit('供应商期初') as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
					//'供应商编码', '供应商', '应付金额', '其他应付金额', '预付金额', '期初余额', '结算日期', '业务员', '备注'
					$supplier             = query('supplier', " coid = '" . self::$coid . "' AND code = '$cell[供应商编码]' ");
					$where                = " coid = '" . self::$coid . "' AND type = '供应商' AND typeId = '{$supplier['id']}' ";
					$current_unit_default = query('current_unit_default', $where);
					$record               = query("record", " coid = '" . self::$coid . "' and type = '供应商' and typeId = '$supplier[id]' ");
					if (!$supplier['id']) {
						$text .= "供应商期初导入失败：第【{$row_list}】行无此供应商<br>";
					} elseif ($record['id']) {
						$text .= "供应商期初导入失败：第【{$row_list}】行此供应商已存在账户变动记录<br>";
					} else {
						$this->startTrans();
						$field = [
							'coid'            => self::$coid,
							'type'            => '供应商',
							'typeId'          => $supplier['id'],
							'target_no'       => $supplier['code'],
							'target_name'     => $supplier['name'],
							'should_money'    => self::formattingFigure(floatval($cell['应付金额'])),
							'other_money'     => self::formattingFigure(floatval($cell['其他应付金额'])),
							'advance_money'   => self::formattingFigure(floatval($cell['预付金额'])),
							'balance'         => self::formattingFigure(floatval($cell['期初余额'])),
							'settlement_date' => is_numeric($cell['结算日期']) ? date("Y-m-d", $cell['结算日期']) :$cell['结算日期'],
							'salesman'        => $cell['业务员'],
							'text'            => $cell['备注'],
							'time'            => $this->time,
						];
						if (static::isNull($current_unit_default['id'])) {
							$field = array_merge($field, [
								'id' => self::getNo(),
							]);
							$warn  = static::insert(["table" => 'current_unit_default', "field" => $field,]);
						} else {
							$field['id'] = $current_unit_default['id'];
							$warn        = static::update(["table" => 'current_unit_default', "field" => $field, 'where' => " id = '" . $current_unit_default['id'] . "' "]);
						}
						if (in_array($warn, ['新增成功', '更新成功'])) {
							//插入账户变动表
							$supplierRecord = query('record', " coid = '" . self::$coid . "' and type = '供应商' and typeId = '$supplier[id]' and sourceTable = 'current_unit_default' and sourceId = '$current_unit_default[id]' ");
							$field          = [
								'coid'        => self::$coid,
								'type'        => '供应商',
								'typeId'      => $supplier['id'],
								'targetDate'  => $field['settlement_date'],
								'classify'    => '供应商期初',
								'direction'   => '-',
								'money'       => $field['balance'] > 0 ? -1 * $field['balance'] : abs($field['balance']),
								'balance'     => $field['balance'] > 0 ? -1 * $field['balance'] : abs($field['balance']),
								'sourceTable' => 'current_unit_default',
								'sourceId'    => $field['id'],
								'text'        => $field['text'],
								'stName'      => $this->control['name'],
								'hiddenText'  => $this->date . '供应商期初导入',
								'time'        => $this->time,
							];
							if (static::isNull($supplierRecord['id'])) {
								$warn = static::insert(["table" => 'record', "field" => $field,]);
							} else {
								$warn = static::update(["table" => 'record', "field" => $field, 'where' => " id = '" . $supplierRecord['id'] . "' "]);
							}
							if (in_array($warn, ['新增成功', '更新成功'])) {
								$this->commitTrans();
								// 更新数量
								$x++;
								$text .= "第【{$row_list}】行导入成功<br>";
							} else {
								$this->rollback();
							}
						} else {
							$this->rollback();
							$text .= "第【{$row_list}】行导入失败：插入失败<br>";
						}
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$this->logText(["type" => 'supplierDefault', "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}

	/**
	 * 导出
	 */
	public function exportSupplierData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		if (!$this->power('supplierDefault', 'export')) {
			$_SESSION['warn'] = '您还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => 'current_unit_default',
                    "where" => "id in ('".implode("','", $checkedId)."') order by list desc",
                ))['array'];
            }else{
                $sql   = $_SESSION['supplierDefault']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '供应商编码'=>$array['target_no'],
                            '供应商'=>$array['target_name'],
                            '应付金额'=>self::lostZero($array['should_money']),
                            '其他应付金额'=> self::lostZero($array['other_money']),
                            '预付金额'=> self::lostZero($array['advance_money']),
                            '期初余额'=>self::lostZero($array['balance']),
                            '结算日期'=>$array['settlement_date'],
                            '业务员'=>$array['salesman'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = $this->control['name'] . "导出了供应商期初设置";
			$this->logText(["type" => 'supplierDefault', "text" => $text]);
			$this->excelOut($title, $data, '供应商期初设置.xlsx');
			exit(0);
		}
		$locationUrl = root . 'control/adIndex.html?cla=' . $this->get['cla'] . '&fun=home';
		header("Location:" . $locationUrl);
	}
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '客户期初'=>[
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户',
                    'aliasName'=>'客户',
                ],
                [
                    'columnName'=>'应收金额',
                    'aliasName'=>'应收金额',
                ],
                [
                    'columnName'=>'其他应收金额',
                    'aliasName'=>'其他应收金额',
                ],
                [
                    'columnName'=>'预收金额',
                    'aliasName'=>'预收金额',
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额',
                ],
                [
                    'columnName'=>'结算日期',
                    'aliasName'=>'结算日期',
                ],
                [
                    'columnName'=>'业务员',
                    'aliasName'=>'业务员',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ],
            '供应商期初'=>[
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商',
                    'aliasName'=>'供应商',
                ],
                [
                    'columnName'=>'应付金额',
                    'aliasName'=>'应付金额',
                ],
                [
                    'columnName'=>'其他应付金额',
                    'aliasName'=>'其他应付金额',
                ],
                [
                    'columnName'=>'预付金额',
                    'aliasName'=>'预付金额',
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额',
                ],
                [
                    'columnName'=>'结算日期',
                    'aliasName'=>'结算日期',
                ],
                [
                    'columnName'=>'业务员',
                    'aliasName'=>'业务员',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'物料分类',
                    'aliasName'=>'物料分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'主单位期初数量',
                    'aliasName'=>'主单位期初数量',
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价（元）',
                ],
                [
                    'columnName'=>'总价',
                    'aliasName'=>'总价（元）',
                ],
            ]
        };
    }
}
